//package org.thingsboard.server.config.oauth2;
//
//import com.auth0.jwt.JWT;
//import com.auth0.jwt.interfaces.DecodedJWT;
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import io.jsonwebtoken.Claims;
//import io.jsonwebtoken.Jwts;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.core.ParameterizedTypeReference;
//import org.springframework.core.convert.converter.Converter;
//import org.springframework.http.*;
//import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
//import org.springframework.security.authentication.AuthenticationProvider;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationProvider;
//import org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken;
//import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
//import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
//import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
//import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
//import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
//import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequestEntityConverter;
//import org.springframework.security.oauth2.core.OAuth2AccessToken;
//import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
//import org.springframework.security.oauth2.core.OAuth2AuthorizationException;
//import org.springframework.security.oauth2.core.OAuth2Error;
//import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
//import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
//import org.springframework.security.oauth2.core.user.OAuth2User;
//import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
//import org.springframework.stereotype.Component;
//import org.springframework.util.Assert;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.util.StringUtils;
//import org.springframework.web.client.*;
//import org.springframework.web.context.request.RequestContextHolder;
//import org.springframework.web.context.request.ServletRequestAttributes;
//import org.springframework.web.util.UriComponentsBuilder;
//import org.thingsboard.server.common.data.Customer;
//import org.thingsboard.server.common.data.CustomerConfig;
//import org.thingsboard.server.common.data.User;
//import org.thingsboard.server.common.data.id.CustomerId;
//import org.thingsboard.server.common.data.id.TenantId;
//import org.thingsboard.server.common.data.security.Authority;
//import org.thingsboard.server.common.data.security.UserCredentials;
//import org.thingsboard.server.common.data.security.model.JwtToken;
//import org.thingsboard.server.dao.customer.CustomerConfigService;
//import org.thingsboard.server.dao.customer.CustomerService;
//import org.thingsboard.server.dao.user.UserService;
//import org.thingsboard.server.service.security.auth.JwtAuthenticationToken;
//import org.thingsboard.server.service.security.auth.jwt.RefreshTokenRepository;
//import org.thingsboard.server.service.security.auth.oauth2.HttpCookieOAuth2AuthorizationRequestRepository;
//import org.thingsboard.server.service.security.model.SecurityUser;
//import org.thingsboard.server.service.security.model.UserPrincipal;
//import org.thingsboard.server.service.security.model.token.AccessJwtToken;
//import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
//import org.thingsboard.server.service.security.model.token.RawAccessJwtToken;
//import org.thingsboard.server.utils.AdvancedEncryption;
//import org.thingsboard.server.utils.MapCacheUtil;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.net.URI;
//import java.util.*;
//
//@Slf4j
//public class CustomOauthUserService extends DefaultOAuth2UserService {
//    private RestOperations restOperations;
//
//    private SecurityUser securityUser;
//
//    @Resource
//    CustomerConfigService customerConfigService;
//
//    @Resource
//    protected UserService userService;
//
//    @Resource
//    private MapCacheUtil mapcacheutil;
//
//    @Resource
//    protected CustomerService customerService;
//
//    @Resource
//    private JwtTokenFactory tokenFactory;
//
//    @Value("${security.oauth2.clients.default.clientId}")
//    private String clientId;
//    @Value("${security.oauth2.clients.default.clientSecret}")
//    private String clientSecret;
//    @Value("${security.oauth2.clients.default.accessTokenUri}")
//    private String accessTokenUri;
//    @Value("${security.oauth2.clients.default.scope}")
//    private String scope;
//    @Value("${security.oauth2.clients.default.redirectUriTemplate}")
//    private String redirectUriTemplate;
//    @Value("${security.oauth2.clients.default.authorizationGrantType}")
//    private String authorizationGrantType;
//    @Value("${security.oauth2.clients.default.homeUri}")
//    private String homeUri;
//    @Value("${security.oauth2.clients.default.mapperConfig.basic.defaultEmail}")
//    private String defaultEmail;
//    @Value("${security.oauth2.clients.default.mapperConfig.basic.algorithm}")
//    private String algorithm;
//    @Value("${security.oauth2.clients.default.mapperConfig.basic.algorithmKey}")
//    private String key;
//    @Resource
//    private BCryptPasswordEncoder passwordEncoder;
//    @Resource
//    private RefreshTokenRepository refreshTokenRepository;
//
//    @Resource
//    private HttpCookieOAuth2AuthorizationRequestRepository httpCookieOAuth2AuthorizationRequestRepository;
//
//    private static final ParameterizedTypeReference<Map<String, Object>> PARAMETERIZED_RESPONSE_TYPE = new ParameterizedTypeReference<Map<String, Object>>() {
//    };
//
//    ObjectMapper objectMapper;
//    public CustomOauthUserService() {
//        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.getMessageConverters().add(new PlainTextttpMessageConverter());
//        restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
//        this.restOperations = restTemplate;
//        this.objectMapper=new ObjectMapper();
//    }
//
//
//
//    private static final String MISSING_USER_INFO_URI_ERROR_CODE = "missing_user_info_uri";
//
//    private static final String MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE = "missing_user_name_attribute";
//
//    private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response";
//    @Override
//    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
//        log.info("测试userRequest中是否包含token ---------------------------> {}", userRequest.getAccessToken());
////        if (!StringUtils.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
////            OAuth2Error oauth2Error = new OAuth2Error("missing_user_info_uri", "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), (String)null);
////            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
////        } else {
////            String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
////            if (!StringUtils.hasText(userNameAttributeName)) {
////                OAuth2Error oauth2Error = new OAuth2Error("missing_user_name_attribute", "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), (String)null);
////                throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
////            } else {
////                RequestEntity<?> request = (RequestEntity)this.requestEntityConverter.convert(userRequest);
////                ResponseEntity<Map<String, Object>> response = this.getResponse(userRequest, request);
////                Map<String, Object> userAttributes = (Map)response.getBody();
////                Set<GrantedAuthority> authorities = new LinkedHashSet();
////                log.info("userAttributes中包含的数据 --------------------------------> {}", userAttributes.toString());
////                authorities.add(new OAuth2UserAuthority(userAttributes));
////                OAuth2AccessToken token = userRequest.getAccessToken();
////
////                for(String authority : token.getScopes()) {
////                    authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
////                }
////
////                return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
////            }
////        }
////        OAuth2User oAuth2User = super.loadUser(userRequest);
////        return oAuth2User;
////        OAuth2AccessToken oAuth2AccessToken = null;
//        try {
//            if (!StringUtils
//                    .hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
//                OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE,
//                        "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: "
//                                + userRequest.getClientRegistration().getRegistrationId(),
//                        null);
//                throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
//            }
//            String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint()
//                    .getUserNameAttributeName();
//            if (!StringUtils.hasText(userNameAttributeName)) {
//                OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE,
//                        "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: "
//                                + userRequest.getClientRegistration().getRegistrationId(),
//                        null);
//                throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
//            }
//
//
//            OAuth2AccessToken accessToken = userRequest.getAccessToken();
//            Claims decode;
//            decode = parseJWT(accessToken.getTokenValue());
//            String username = getUsernameFromToken(decode);
//            TenantId devOpsId = getTenantIdFromUsername(username);
//
//            RequestEntity<?> request = this.requestEntityConverter.convert(userRequest);
//            ResponseEntity<String> response = getResponse(userRequest, request);
//            String yserrsp = response.getBody();
//            DecodedJWT decode1 = JWT.decode(yserrsp);
//            Map userAttributes =getuserinfo(decode1);
//            userAttributes.put("devOpsId",devOpsId);
//            userAttributes.put("username",username);
////
//            Set<GrantedAuthority> authorities = new LinkedHashSet<>();
//            authorities.add(new OAuth2UserAuthority(userAttributes));
//            OAuth2AccessToken token = userRequest.getAccessToken();
//            for (String authority : token.getScopes()) {
//                authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
//            }
//            processToken(username, devOpsId, response, request);
//            return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
//        } catch (Exception e) {
//            handleException(e);
//        }
//        return null;
//    }
//
//    private void handleException(Exception e) {
//        throw new RuntimeException("根据邮箱查询租户出错或新建租户出错", e);
//    }
//
////    private OAuth2AccessToken exchangeToken(String code) {
////        log.info("重写自定义认证 - " + code);
////        RestTemplate restTemplate = new RestTemplate();
////        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
////        HttpHeaders headers = new HttpHeaders();
////        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
////        LinkedMultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
////        multiValueMap.add("code", code);
////        multiValueMap.add("grant_type", authorizationGrantType);
////        multiValueMap.add("redirect_uri", redirectUriTemplate);
////        multiValueMap.add("scope", scope);
////        multiValueMap.add("client_id", clientId);
////        multiValueMap.add("client_secret", clientSecret);
////        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(multiValueMap, headers);
////        log.info("开始向oauth2认证 - " + multiValueMap.toString());
////        ResponseEntity<OAuth2AccessToken> responseEntity = null;
////        OAuth2AccessToken oAuth2AccessToken;
////        try {
////            responseEntity = restTemplate.exchange(
////                    accessTokenUri,
////                    HttpMethod.POST,
////                    httpEntity,
////                    OAuth2AccessToken.class
////            );
////            log.info("auth2认证成功" + multiValueMap.toString());
////            oAuth2AccessToken = responseEntity.getBody();
////            log.info("获取token信息 - " + oAuth2AccessToken.toString());
////            return oAuth2AccessToken;
////        } catch (RestClientException e) {
////            throw new RuntimeException("auth2认证失败", e);
////        }
////    }
//
//    private void processToken(String username, TenantId devOpsId, HttpServletResponse response, HttpServletRequest request) throws Exception {
//        List<CustomerConfig> customerConfigList = customerConfigService.findCustomerConfigByUsername(username);
//
//        if (customerConfigList.size() == 1) {
//            // 处理单个用户情况
//            processSingleUser(customerConfigList.get(0), username, devOpsId, response, request);
//        } else if (customerConfigList.size() > 1) {
//            // 处理多个用户情况
//            processMultipleUsers(customerConfigList, username, response);
//        } else {
//            log.info("无对应处理中心租户信息:" + username);
//            response.sendRedirect(homeUri + "/login/selectUser");
//        }
//    }
//
//    private void processMultipleUsers(List<CustomerConfig> customerConfigList, String username, HttpServletResponse response) throws Exception {
//        customerConfigList.forEach(x -> {
//            mapcacheutil.add(x.getLoginUser().concat(x.getOrgUser()), x.getAuthority(), 60000);
//        });
//        response.sendRedirect(homeUri + "/login/selectUser?usertoken=" + AdvancedEncryption.encryptString(username, algorithm, key));
//    }
//
//    private void processSingleUser(CustomerConfig customerConfig, String username, TenantId devOpsId, HttpServletResponse response, HttpServletRequest request) throws IOException {
//        String orgUserName = customerConfig.getOrgUser();
//        String authority = customerConfig.getAuthority();
//        log.info("Org User: " + orgUserName);
//
//        User user = userService.findUserByEmail(devOpsId, orgUserName.concat("defaultEmail"));
//        if (user == null) {
//            log.info("无对应处理中心租户信息:" + username);
//            response.sendRedirect(homeUri + "/login/selectUser");
//        } else {
//            if (authority.equals(Authority.TENANT_ADMIN.name())) {
//                log.info("租户已存在 - " + user.toString());
//                response.sendRedirect(oauthTokenLogin(user, request, response));
//            } else {
//                response.sendRedirect(oauthTokenLogin(getOrCreateCustomer(user, username), request, response));
//            }
//        }
//    }
//
//    private CustomerId getCustomerId(TenantId tenantId, String customerName) {
//        if (StringUtils.isEmpty(customerName)) {
//            return null;
//        }
//        Optional<Customer> customerOpt = customerService.findCustomerByTenantIdAndTitle(tenantId, customerName);
//        if (customerOpt.isPresent()) {
//            return customerOpt.get().getId();
//        } else {
//            Customer customer = new Customer();
//            customer.setTenantId(tenantId);
//            customer.setTitle(customerName);
//            return customerService.saveCustomer(customer).getId();
//        }
//    }
//
//    private User getOrCreateCustomer(User user, String oldName) {
//        //判断处理中心租户是否存在，存在则以devops用户作为登录用户，登录租户下的用户
//        User customerUser = new User();
//        if (user != null) {
//            boolean equals = user.getCustomerId().getId().toString().equals(TenantId.SYS_TENANT_ID.getId().toString());
//            CustomerId customerId = user.getCustomerId() != null && !equals ?
//                    user.getCustomerId() : getCustomerId(user.getTenantId(), oldName.concat(defaultEmail));
//            String customer = user.getEmail();//oldName.concat("_").concat(user.getEmail());
//            customerUser.setEmail(customer);
//            customerUser.setCustomerId(customerId);
//            customerUser.setAuthority(Authority.CUSTOMER_USER);
//            TenantId tenantId = user.getTenantId();
//            customerUser.setTenantId(tenantId);
//            User loginCustomer = userService.findUserByEmail(tenantId, customer);
//            if (loginCustomer == null) {
//                customerUser = userService.saveUser(customerUser.getTenantId(),customerUser);
//                log.info("创建用户 - " + customerUser.toString());
//                UserCredentials userCredentials = userService.findUserCredentialsByUserId(customerUser.getTenantId(), customerUser.getId());
//                if (userCredentials == null) {
//                    userService.activateUserCredentials(customerUser.getTenantId(), userCredentials.getActivateToken(), passwordEncoder.encode(""));
//                }
//            } else {
//                customerUser = loginCustomer;
//            }
//        }
//        return customerUser;
//    }
//
//    private String oauthTokenLogin(User saveUser, HttpServletRequest request, HttpServletResponse response) {
//        //登录
//        JwtToken accessToken;
//        JwtToken refreshToken;
//        try {
//            UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, saveUser.getEmail());
//            SecurityUser securityUser = new SecurityUser(saveUser, true, principal);
//            AccessJwtToken accessToken1 = (AccessJwtToken) tokenFactory.createAccessJwtToken(securityUser);
//            accessToken= new JwtToken() {
//                @Override
//                public String getToken() {
//                    return accessToken1.getToken();
//                }
//            } ;
//            refreshToken = refreshTokenRepository.requestRefreshToken(securityUser);
//        } catch (Exception e) {
//            log.error("Can't get or create security user from oauth2 user", e);
//            throw new RuntimeException("Can't get or create security user from oauth2 user", e);
//        }
//        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(homeUri);
//        builder.path("/");
//        builder.queryParam("accessToken", accessToken);
//        builder.queryParam("refreshToken", refreshToken);
//        URI location = builder.build().toUri();
//        log.info("重定向 - " + location.toString());
//        return homeUri + "/home/?accessToken=" + accessToken.getToken()
//                + "&refreshToken=" + refreshToken.getToken();
//    }
//
//    private String getUsernameFromToken(Claims decode) {
//        String username = decode.get("username", String.class);
//        log.info("用户名 - " + username);
//        return username;
//    }
//
//    private Claims parseJWT(String token) {
//        try {
//            // 解析token、获得claims、jwt中荷载中申明的对象
//            Claims claims = (Claims) Jwts.parser()
//                    .setSigningKey("1234")
//                    .parse(token)
//                    .getBody();
//
//            return  claims;
//        } catch (Exception e) {
//            throw new RuntimeException("解析token失败" + token, e);
//        }
//    }
//
//    private ResponseEntity<String> getResponse(OAuth2UserRequest userRequest, RequestEntity<?> request) {
//        try {
//            return this.restOperations.exchange(request, String.class);
//        }
//        catch (OAuth2AuthorizationException ex) {
//            OAuth2Error oauth2Error = ex.getError();
//            StringBuilder errorDetails = new StringBuilder();
//            errorDetails.append("Error details: [");
//            errorDetails.append("UserInfo Uri: ")
//                    .append(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri());
//            errorDetails.append(", Error Code: ").append(oauth2Error.getErrorCode());
//            if (oauth2Error.getDescription() != null) {
//                errorDetails.append(", Error Description: ").append(oauth2Error.getDescription());
//            }
//            errorDetails.append("]");
//            oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE,
//                    "An error occurred while attempting to retrieve the UserInfo Resource: " + errorDetails.toString(),
//                    null);
//            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
//        }
//        catch (UnknownContentTypeException ex) {
//            String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '"
//                    + userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri()
//                    + "': response contains invalid content type '" + ex.getContentType().toString() + "'. "
//                    + "The UserInfo Response should return a JSON object (content type 'application/json') "
//                    + "that contains a collection of name and value pairs of the claims about the authenticated End-User. "
//                    + "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '"
//                    + userRequest.getClientRegistration().getRegistrationId() + "' conforms to the UserInfo Endpoint, "
//                    + "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'";
//            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage, null);
//            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
//        }
//        catch (RestClientException ex) {
//            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE,
//                    "An error occurred while attempting to retrieve the UserInfo Resource: " + ex.getMessage(), null);
//            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
//        }
//    }
//
//    private Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = new OAuth2UserRequestEntityConverter();
//
//
//    HashMap    getuserinfo(DecodedJWT d){
//        String payload = d.getPayload();
//        try {
//
//            String decode = new String( Base64.getDecoder().decode(payload));
//            HashMap u = objectMapper.readValue(decode, HashMap.class);
//
//            return u;
//        } catch (JsonProcessingException e) {
//            return null;
//        }
////     {"sub":"7162594941741301760",
////         "aud":"d6e93e36092c4950b6589730da9099b3",
////         "grant_type":"authorization_code",
////         "user_id":7162594941741301760,
////         "is_refresh_token":0,
////         "iss":"http://platform.paas2.chinapost.com.cn",
////         "name":"ç\u008e\u008bå°\u0091è\u0087£",
////         "exp":1689325375,
////         "is_service_user":0,
////         "jti":"f7cd05ff-7bff-491b-a651-5226180b251c",
////         "sid":"52ae54b1-16f8-4255-aa5d-682d4b4d4ee4",
////         "username":"wangshaochen"}
//    }
//
//
//    private String getUsernameFromToken(DecodedJWT decode) {
//        String username = decode.getClaim("username").asString();
//        username = "sdyz_futianshun";
//        return username;
//    }
//
//
//
//
//
//    private TenantId getTenantIdFromUsername(String username) {
//        return new TenantId(UUID.nameUUIDFromBytes(username.getBytes()));
//    }
//
//}
